package verify

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"sort"
	"strings"

	"github.com/tidwall/gjson"
)

// var params = map[string]string{}
var params = map[string]string{
	"mod":          "samsung(sm-g530h)",
	"lon":          "116.41025",
	"country_code": "cn",
	"did":          "ANDROID_44837cdd5405b542",
	"app":          "0",
	"net":          "WIFI",
	"oc":           "ALI_CPD",
	"ud":           "0",
	"c":            "ALI_CPD",
	"sys":          "ANDROID_5.1.1",
	"appver":       "5.6.1.5927",
	"language":     "zh-cn",
	"lat":          "39.916411",
	"ver":          "5.6",
	"max_memory":   "192",
}

func Verify(_photoId, _authorId, user_id, method string) bool {
	switch method {
	case "web":
		return verifyWeb(_photoId, _authorId)
	case "app":
		return verifyApp(_photoId, _authorId, user_id)
	default:
		return false
	}

}

func verifyWeb(_photoId, _authorId string) bool {
	post_url := "https://live.kuaishou.com/graphql"
	post_data := `{"operationName":"commentListQuery","variables":{"pcursor":"","photoId":"` + _photoId + `","page":1,"count":200},"query":"query commentListQuery($photoId: String, $page: Int, $pcursor: String, $count: Int) {\n  shortVideoCommentList(photoId: $photoId, page: $page, pcursor: $pcursor, count: $count) {\n    commentCount\n    realCommentCount\n    pcursor\n    commentList {\n      commentId\n      authorId\n      authorName\n      content\n      headurl\n      timestamp\n      authorEid\n      status\n      subCommentCount\n      subCommentsPcursor\n      likedCount\n      liked\n      subComments {\n        commentId\n        authorId\n        authorName\n        content\n        headurl\n        timestamp\n        authorEid\n        status\n        replyToUserName\n        replyTo\n        replyToEid\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n"}`
	var jsonstr = []byte(post_data)
	buffer := bytes.NewBuffer(jsonstr)

	request, err := http.NewRequest("POST", post_url, buffer)
	if err != nil {
		fmt.Printf("http.NewRequest%v", err)
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("Host", "live.kuaishou.com")
	// request.Header.Set("Cookie", "clientid=3; did=web_31d825c96c574e68a99a8822c16502d6; client_key=65890b29; didv=1572244476000; Hm_lvt_86a27b7db2c5c0ae37fee4a8a35033ee=1574050417,1575263631; userId=101559898; kuaishou.live.bfb1s=9b8f70844293bed778aade6e0a8f9942; kuaishou.live.web_st=ChRrdWFpc2hvdS5saXZlLndlYi5zdBKgAV35io3fbIF3ehyNjAaViODlYvIZnMbmEY68ioS6fQpOvh2FFS8uBCRBTSN8JIzsez__sJIE8SZC5p7UvQ7TpJYjY7we0AOhKVRVf-PV07sYEisKzzD1gR87rEDWlbbBE8qbtpr4cFrqf6ZexAvkdTZaBbsLpX_trGLjsIHesof6RxuBdmV81cb16iiVrXGr0P2ntPoe9TuM8WODwIUweOUaEo_d-PiuxE4duU2DjxXdbB5BSiIgpz_Lzg_9EMOsxf7kLibg-n0sqwLzmKMfdctAjxTScLkoBTAB; kuaishou.live.web_ph=4b4aaa7fc417c55237313a7b197ecb2f8338; userId=101559898")
	request.Header.Set("Origin", "https://live.kuaishou.com")
	request.Header.Set("Referer", "https://live.kuaishou.com/u/3xspystm9se57nq/"+_authorId)
	request.Header.Set("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0")

	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Printf("client.Do%v", err)
	}
	defer resp.Body.Close()

	fmt.Println(resp.Request)
	respBytes, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Printf("ioutil.ReadAll%v", err)
	}
	fmt.Println(string(respBytes))

	value := gjson.Get(string(respBytes), "data.shortVideoCommentList.commentList.#(authorId=\""+_authorId+"\")")
	return len(value.String()) > 0
}

func verifyApp(_photoId, _authorId, _userId string) bool {
	post_url := "http://api3.gifshow.com/rest/n/comment/list/v2"
	post_data := map[string]string{
		"photoId":    _photoId,
		"user_id":    _authorId,
		"order":      "desc",
		"count":      "10",
		"client_key": "3c2cd3f3",
		"os":         "android",
	}
	post_data["sig"] = getGifSign(post_data)
	// req := HttpRequest.NewRequest()
	// req.SetHeaders(map[string]string{
	// 	"X-REQUESTID":     "230896",
	// 	"User-Agent":      "kwai-android",
	// 	"Connection":      "keep-alive",
	// 	"Accept-Language": "zh-cn",
	// 	"Content-Type":    "application/x-www-form-urlencoded;charset=UTF-8",
	// 	"Host":            "api3.gifshow.com",
	// 	"Accept-Encoding": "gzip",
	// })
	// post_url = url_add_params(post_url)
	// res, _ := req.Post(post_url, post_data)
	// _body, err := res.Body()
	// if err != nil {
	// 	fmt.Println(err)
	// }
	// fmt.Println(string(_userId))
	// fmt.Println(string(_body))
	// time.Sleep(time.Second)
	// return true

	// var jsonstr, _ = json.Marshal(post_data)
	data := url.Values{}
	for key, value := range post_data {
		data.Set(key, value)
	}

	request, err := http.NewRequest("POST", post_url, strings.NewReader(data.Encode()))
	if err != nil {
		fmt.Printf("http.NewRequest%v", err)
	}
	url_with_params(request)
	request_with_data(request)
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Printf("client.Do%v", err)
	}
	defer resp.Body.Close()
	respBytes, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Printf("ioutil.ReadAll%v", err)
	}
	fmt.Println(strings.Index(string(respBytes), _userId) >= 0)
	return strings.Index(string(respBytes), _userId) >= 0
}

func url_with_params(request *http.Request) {
	params_add := url.Values{}
	for key, value := range params {
		params_add.Set(key, value)
	}
	request.URL.RawQuery = params_add.Encode()
}

func url_add_params(post_url string) string {
	post_url += "?"
	for key, value := range params {
		post_url = post_url + key + "=" + value + "&"
	}
	return post_url
}

func request_with_data(request *http.Request) {
	headers := map[string]string{
		"X-REQUESTID":     "230896",
		"User-Agent":      "kwai-android",
		"Connection":      "keep-alive",
		"Accept-Language": "zh-cn",
		"Content-Type":    "application/x-www-form-urlencoded",
		"Host":            "api3.gifshow.com",
	}

	for key, value := range headers {
		request.Header.Set(key, value)
	}
}

func getGifSign(t_data map[string]string) string {
	var data = map[string]string{}
	for key, value := range t_data {
		data[key] = value
	}
	for key, value := range params {
		data[key] = value
	}
	keys := sortKeys(data)

	m_str := ""
	for _, key := range keys {
		m_str = m_str + key + "=" + data[key]
	}
	sign := md5V(m_str + "382700b563f4")
	return sign
}

func sortKeys(data map[string]string) []string {
	var key_slice []string
	for key, _ := range data {
		key_slice = append(key_slice, key)
	}
	sort.Strings(key_slice)
	return key_slice
}

func md5V(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}
